package bb.lanxing.lib.devices.sync;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.garmin.fit.Decode;
import com.garmin.fit.FitRuntimeException;
import com.garmin.fit.Mesg;
import com.garmin.fit.SessionMesg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread;
import java.util.Locale;

import bb.lanxing.lib.devices.utils.FitUtils;

public class FitManager {
    public static final int OP_DECODE_FIT = 2;
    public static final int OP_SAVE_TMP_FILE = 2;
    public static final int OP_WRITE_FILE = 1;
    private FitManagerCallback mCallback;
    private boolean mCanceled;
    private Decode mFitDecoder;
    private File mFitFileDir;
    private FitHandler mHandler;
    final String TAG = "FitManager";
    final String FIT_SUFFIX = ".fit";
    final String FIT_TMP_SUFFIX = ".fit.tmp";


    public interface FitManagerCallback {
        void onError(FitTrans fitTrans, Throwable th);

        void onFitReceived(FitTrans fitTrans);

        void onMesg(FitTrans fitTrans, Mesg mesg);

        void onSport(FitTrans fitTrans, SessionMesg sessionMesg);
    }

    public FitManager(String str, FitManagerCallback fitManagerCallback) {
        this.mCallback = fitManagerCallback;
        this.mFitFileDir = str != null ? new File(str) : null;
    }

    private void init() {
        synchronized (this) {
            if (this.mHandler != null) {
                return;
            }
            HandlerThread handlerThread = new HandlerThread("fit-manager");
            handlerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread thread, Throwable th) {
                    th.printStackTrace();
                }
            });
            handlerThread.start();
            FitHandler fitHandler = new FitHandler(handlerThread.getLooper());
            this.mHandler = fitHandler;
            fitHandler.fitManager = this;
        }
    }

    public void write(FitTrans fitTrans) {
        init();
        fitTrans.path = String.format(Locale.getDefault(), "%s%c%s%s",
                this.mFitFileDir.getAbsolutePath(), File.separatorChar, fitTrans.id, ".fit.tmp");
        this.mHandler.sendMessage(this.mHandler.obtainMessage(1, fitTrans));
    }

    void _write(FitTrans paramFitTrans) {
        FitRuntimeException fitRuntimeException1 = null;
        FitRuntimeException fitRuntimeException3 = null;
        FileOutputStream fileOutputStream2 = null;
        byte[] arrayOfByte = null;
//        FitRuntimeException fitRuntimeException2 = fitRuntimeException3;
        FileOutputStream fileOutputStream1 = fileOutputStream2;
        try {
            if (paramFitTrans.playload != null) {
//                fitRuntimeException2 = fitRuntimeException3;
//                fileOutputStream1 = fileOutputStream2;
                arrayOfByte = (byte[])paramFitTrans.playload;
//                fitRuntimeException2 = fitRuntimeException3;
//                fileOutputStream1 = fileOutputStream2;
                FileOutputStream fileOutputStream = new FileOutputStream(paramFitTrans.path);
//                fitRuntimeException2 = fitRuntimeException3;
//                fileOutputStream1 = fileOutputStream2;
//                this(paramFitTrans.path, true);
                try {
                    fileOutputStream.write(arrayOfByte, 0, arrayOfByte.length);
                    fileOutputStream.close();
                    StringBuilder stringBuilder = new StringBuilder();
//                    this();
                    stringBuilder.append("Write file: ");
                    stringBuilder.append(paramFitTrans.path);
                    Log.d("FitManager", stringBuilder.toString());
                    FileOutputStream fileOutputStream3 = fileOutputStream;
                } catch (IOException | FitRuntimeException iOException) {
                    fileOutputStream1 = fileOutputStream;
                }
            }
//            fitRuntimeException2 = fitRuntimeException;
//            fitRuntimeException1 = fitRuntimeException;
            if (paramFitTrans.completed) {
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
                File file1 = new File(paramFitTrans.path);
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
//                this(paramFitTrans.path);
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
                if (!paramFitTrans.ignoreCRC) {
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    if (!FitUtils.checkFitFile(file1, false)) {
//                        fitRuntimeException2 = fitRuntimeException;
//                        fitRuntimeException1 = fitRuntimeException;
                        FitRuntimeException fitRuntimeException4 = new FitRuntimeException();
//                        fitRuntimeException2 = fitRuntimeException;
//                        fitRuntimeException1 = fitRuntimeException;
//                        this("CRC ERROR");
//                        fitRuntimeException2 = fitRuntimeException;
//                        fitRuntimeException1 = fitRuntimeException;
                        throw fitRuntimeException4;
                    }
                }
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
                String str = paramFitTrans.path.substring(0, paramFitTrans.path.lastIndexOf("."));
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
                File file2 = new File(str);
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
//                this(str);
//                fitRuntimeException2 = fitRuntimeException;
//                fitRuntimeException1 = fitRuntimeException;
                if (file1.renameTo(file2)) {
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    if (this.mCallback != null) {
//                        fitRuntimeException2 = fitRuntimeException;
//                        fitRuntimeException1 = fitRuntimeException;
                        paramFitTrans.path = str;
//                        fitRuntimeException2 = fitRuntimeException;
//                        fitRuntimeException1 = fitRuntimeException;
                        this.mCallback.onFitReceived(paramFitTrans);
                    }
                } else {
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    IOException iOException = new IOException();
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    StringBuilder stringBuilder = new StringBuilder();
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
//                    this();
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    stringBuilder.append("Failed to rename ");
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    stringBuilder.append(paramFitTrans.path);
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
//                    this(stringBuilder.toString());
//                    fitRuntimeException2 = fitRuntimeException;
//                    fitRuntimeException1 = fitRuntimeException;
                    throw iOException;
                }
            }
        } catch (IOException iOException) {
            Log.e("FitManager", "", iOException);
            clear(false);
            error(paramFitTrans, iOException);
        } catch (FitRuntimeException fitRuntimeException) {
//            fitRuntimeException1 = fitRuntimeException2;
        }
    }

    private void error(FitTrans fitTrans, Throwable th) {
        FitManagerCallback fitManagerCallback = this.mCallback;
        if (fitManagerCallback != null) {
            fitManagerCallback.onError(fitTrans, th);
        }
    }

    private void mesg(FitTrans fitTrans, Mesg mesg) {
        StringBuilder sb = new StringBuilder();
        sb.append("Fit message: ");
        sb.append(mesg != null ? Integer.valueOf(mesg.getNum()) : "done");
        Log.d("FitManager", sb.toString());
        FitManagerCallback fitManagerCallback = this.mCallback;
        if (fitManagerCallback != null) {
            fitManagerCallback.onMesg(fitTrans, mesg);
        }
    }

    private void sportMesg(FitTrans fitTrans, SessionMesg sessionMesg) {
        FitManagerCallback fitManagerCallback = this.mCallback;
        if (fitManagerCallback != null) {
            fitManagerCallback.onSport(fitTrans, sessionMesg);
        }
    }

    public void release() {
        FitHandler fitHandler = this.mHandler;
        if (fitHandler != null) {
            fitHandler.getLooper().quit();
            this.mHandler.fitManager = null;
            this.mHandler = null;
        }
        clear(false);
        this.mFitFileDir = null;
    }

    public void cancel() {
        this.mCanceled = true;
    }

    public void decode(FitTrans fitTrans) {
        init();
        if (fitTrans.path == null) {
            fitTrans.path = String.format(Locale.getDefault(), "%s%c%s%s",
                    this.mFitFileDir.getAbsolutePath(), File.separatorChar, String.valueOf(fitTrans.id), ".fit");
        }
        this.mHandler.sendMessage(this.mHandler.obtainMessage(2, fitTrans));
    }

    void _decode(FitTrans fitTrans) {
        FileInputStream fileInputStream;
        FileInputStream fileInputStream2;
        IOException e;
        if (this.mFitDecoder == null) {
            this.mFitDecoder = new Decode();
        }
        this.mFitDecoder.nextFile();
        FileInputStream fileInputStream3 = null;
        try {
            try {
                try {
                    FileInputStream fileInputStream4 = new FileInputStream(fitTrans.path);
                    try {
                        _decodeSport(fitTrans, fileInputStream4);
                        fileInputStream4.close();
                        fileInputStream2 = new FileInputStream(fitTrans.path);
                        try {
                            this.mFitDecoder.nextFile();
                            Decode.RETURN r3 = Decode.RETURN.CONTINUE;
                            byte[] bArr = new byte[512];
                            while (r3 != Decode.RETURN.END_OF_FILE) {
                                int read = fileInputStream2.read(bArr, 0, 512);
                                if (read == -1) {
                                    break;
                                }
                                for (int i = 0; i < read; i++) {
                                    r3 = this.mFitDecoder.read(bArr[i]);
                                    if (r3 == Decode.RETURN.MESG) {
                                        mesg(fitTrans, this.mFitDecoder.getMesg());
                                    }
                                }
                            }
                            mesg(fitTrans, null);
                            fileInputStream2.close();
                        } catch (FitRuntimeException e2) {
//                            e = e2;
                            if (fitTrans.ignoreDecoderError) {
                                mesg(fitTrans, null);
                            } else {
                                error(fitTrans, e2);
                            }
                            Log.e("FitManager", "", e2);
                            if (fileInputStream2 == null) {
                                return;
                            }
                            fileInputStream2.close();
                        } catch (IOException e3) {
                            e = e3;
                            error(fitTrans, e);
                            Log.e("FitManager", "", e);
                            if (fileInputStream2 == null) {
                                return;
                            }
                            fileInputStream2.close();
                        }
                    } catch (FitRuntimeException e4) {
                        fileInputStream2 = fileInputStream4;
//                        e = e4;
                    } catch (IOException e5) {
                        e = e5;
                        fileInputStream2 = fileInputStream4;
                    } catch (Throwable th) {
//                        th = th;
                        fileInputStream3 = fileInputStream4;
                        try {
                            fileInputStream3.close();
                        } catch (IOException e6) {
                            Log.e("FitManager", "", e6);
                        }
                        throw th;
                    }
                } catch (IOException e7) {
                    Log.e("FitManager", "", e7);
                }
            } catch (FitRuntimeException e8) {
//                e = e8;
                fileInputStream2 = null;
            } catch (Throwable th2) {
//                th = th2;
            }
        } catch (Throwable th3) {
//            th = th3;
//            fileInputStream3 = fileInputStream;
        }
    }


    private void _decodeSport(FitTrans fitTrans, InputStream inputStream) throws IOException {
        Mesg mesg;
        Decode.RETURN r0 = Decode.RETURN.CONTINUE;
        byte[] bArr = new byte[512];
        while (r0 != Decode.RETURN.END_OF_FILE) {
            int read = inputStream.read(bArr, 0, 512);
            if (read == -1) {
                return;
            }
            for (int i = 0; i < read; i++) {
                r0 = this.mFitDecoder.read(bArr[i]);
                if (r0 == Decode.RETURN.MESG && (mesg = this.mFitDecoder.getMesg()) != null && mesg.getNum() == 18) {
                    SessionMesg sessionMesg = new SessionMesg(mesg);
                    if (sessionMesg.getSport() != null) {
                        sportMesg(fitTrans, sessionMesg);
                    }
                }
            }
        }
    }

    public String getPath(String str) {
        if (this.mFitFileDir != null) {
            File file = this.mFitFileDir;
            return new File(file, str + ".fit").getAbsolutePath();
        }
        return null;
    }

    public File findFitFile(String str) {
        File[] listFiles;
        File file = this.mFitFileDir;
        if (file == null || file.list() == null) {
            return null;
        }
        String str2 = str + ".fit";
        for (File file2 : this.mFitFileDir.listFiles()) {
            if (file2.getName().endsWith(str2)) {
                return file2;
            }
        }
        return null;
    }

    public void clear(boolean z) {
        File[] listFiles;
        File file = this.mFitFileDir;
        if (file == null || file.list() == null) {
            return;
        }
        for (File file2 : this.mFitFileDir.listFiles()) {
            if (file2.getName().endsWith(".fit.tmp") || z) {
                file2.delete();
            }
        }
    }

    public static class FitHandler extends Handler {
        FitManager fitManager;

        public FitHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message message) {
            if (this.fitManager == null) {
                return;
            }
            int i = message.what;
            if (i == 1) {
                this.fitManager._write((FitTrans) message.obj);
            } else if (i == 2) {
                this.fitManager._decode((FitTrans) message.obj);
            }
        }
    }

    public static class FitMesg {
        final File file;
        public Mesg fitMesg;
        public final Object playload;

        public FitMesg(File file, Object obj, Mesg mesg) {
            this.file = file;
            this.playload = obj;
            this.fitMesg = mesg;
        }
    }
}
